
# 1,加载系统环境配置
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PMSP.settings.dev')

# 2,django.setup,保证所有的类，都可以使用
import django
django.setup()

# 3，导入生成页面需要的类
from PMSP.utils.my_category import get_category
from contents.models import ContentCategory
from django.shortcuts import loader
from django.conf import settings

# 4，生成页面任务
def generate_static_index_html():
    """
    生成首页静态页面
    :return:
    """
    # 1，获取分类
    categories = get_category()

    # 2,查询广告数据
    contents = {}
    content_category = ContentCategory.objects.order_by("id")
    for category in content_category:
        contents[category.key] = category.contents.all()

    # 3,拼接数据
    contents = {
        "categories":categories,
        "contents":contents
    }

    # 4,获取index模板页面
    template = loader.get_template("index.html")

    # 5,携带contents数据渲染template页面
    html_text = template.render(contents)

    # 6,写入html_text到static文件夹中
    file_path = os.path.join(settings.STATICFILES_DIRS[0],"index.html")

    with open(file_path,'w',encoding='utf-8') as f:
        f.write(html_text)

if __name__ == '__main__':
    generate_static_index_html()